package com.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.common.SetMeta;
import com.shop.common.page.UserPage;
import com.shop.entity.Right;
import com.shop.entity.Role;
import com.shop.exception.UserException;
import com.shop.mapper.ManagerMapper;
import com.shop.entity.Manager;
import com.shop.entity.vo.ManagerRoleVo;
import com.shop.mapper.RightsMapper;
import com.shop.mapper.RoleMapper;
import com.shop.service.ManagerService;
import com.shop.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service("managerService")
public class ManagerServiceImpl implements ManagerService {

    @Autowired
    public ManagerMapper managerMapper;

    @Autowired
    public RoleMapper roleMapper;

    @Autowired
    RightsMapper rightsMapper;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public SetMeta<UserPage<List<ManagerRoleVo>>> selectPage(String query, Integer pageNum, Integer pageSize) {
        if(pageNum <= 0) pageNum = 1;
        if(pageSize <= 0) pageSize = 5;
        Page<ManagerRoleVo> managerPage = managerMapper.selectManageVo(query, new Page<>(pageNum, pageSize));
        List<ManagerRoleVo> managers = managerPage.getRecords();
        UserPage<List<ManagerRoleVo>> userPage = new UserPage<>(managerPage.getTotal(), pageNum, managers);
        SetMeta<UserPage<List<ManagerRoleVo>>> setMeta = new SetMeta<>();
        setMeta.setSuccess(userPage);
        return setMeta;
    }

    /**
     * 根据用户名查找用户
     * @param username
     * @return
     */
    @Override
    public SetMeta<ManagerRoleVo> selectByUsername(String username) throws UserException {
        if(username == null || username == "") throw new UserException("用户名输入错误");
        SetMeta<ManagerRoleVo> setMeta = new SetMeta<>();
        Manager selectOne = managerMapper.selectOne(Wrappers.<Manager>lambdaQuery()
                .eq(Manager::getUsername, username));
        if (selectOne == null) {
            setMeta.setSuccess("用户名不存在");
            return setMeta;
        }
        setMeta.setError("用户名已存在");
        return setMeta;
    }

    /**
     * 添加用户
     * @param managerRoleVo
     * @return
     */
    @Override
    public SetMeta<ManagerRoleVo> insert(ManagerRoleVo managerRoleVo) throws UserException {
        if(managerRoleVo.getPassword() == null || managerRoleVo.getPassword() == "") throw new UserException("用户密码为空");
        SetMeta<ManagerRoleVo> setMeta = new SetMeta<>();


        Date date = new Date();
        managerRoleVo.setType(1);
        managerRoleVo.setMg_time((int) (date.getTime() / 1000));
        managerRoleVo.setCreateTime(date);
        managerRoleVo.setPassword(bCryptPasswordEncoder.encode(managerRoleVo.getPassword()));

        int insert = managerMapper.insert(managerRoleVo);
        if (insert == 1) {
            managerRoleVo.setPassword(null);
            managerRoleVo.setMg_time(null);
            setMeta.setCreated(managerRoleVo,"用户创建成功");
            return setMeta;
        }
        setMeta.setError("用户创建失败");
        return setMeta;
    }

    /**
     * 修改用户状态
     * @param uid
     * @param type
     * @return
     */
    @Override
    public SetMeta<Manager> updateType(Integer uid, Boolean type) {
        SetMeta<Manager> setMeta = new SetMeta<>();
        Manager manager =  managerMapper.selectById(uid);
        manager.setType(type ? 1 : 0);
        int update = managerMapper.update(manager, Wrappers.<Manager>lambdaQuery().eq(Manager::getId, uid));
        if (update == 1) {
            manager.setPassword(null);
            setMeta.setSuccess(manager, "设置状态成功");
            return setMeta;
        }
        setMeta.setError("设置状态失败");
        return setMeta;
    }

    /**
     * 根据ID查询用户信息
     * @param id
     * @return
     */
    @Override
    public SetMeta<Manager> selectOne(Integer id) {
        SetMeta<Manager> setMeta = new SetMeta<>();
        Manager manager = managerMapper.selectOne(Wrappers.<Manager>lambdaQuery().eq(Manager::getId, id));
        if (manager == null) {
            setMeta.setError("查询失败");
            return setMeta;
        }
        manager.setPassword(null);
        manager.setType(null);
        setMeta.setSuccess(manager,"查询成功");
        return setMeta;
    }
    /**
     * 编辑用户提交
     * @param id
     * @param email
     * @param mobile
     * @return
     */
    @Override
    public SetMeta<Manager> updateUser(Integer id, String email, String mobile){
        SetMeta<Manager> setMeta = new SetMeta<>();
        Manager manager = managerMapper.selectById(id);
        manager.setEmail(email == null ? manager.getEmail() : email);
        manager.setMobile(mobile == null ? manager.getMobile() : mobile);
        int update = managerMapper.update(manager, Wrappers.<Manager>lambdaQuery().eq(Manager::getId, id));
        if (update == 1) {
            manager.setPassword(null);
            manager.setType(null);
            setMeta.setSuccess(manager, "更新成功");
            return setMeta;
        }
        setMeta.setError("更新失败");
        return setMeta;
    }

    /**
     * 删除单个用户
     * @param id
     * @return
     */
    @Override
    public SetMeta<Manager> deleteUser(Integer id) {
        SetMeta<Manager> setMeta = new SetMeta<>();
        int delete = managerMapper.delete(Wrappers.<Manager>lambdaQuery().eq(Manager::getId, id));
        if (delete == 1) {
            setMeta.setSuccess("删除成功");
            return setMeta;
        }
        setMeta.setError("删除失败");
        return setMeta;
    }

    /**
     * 分配用户角色
     * @param id
     * @param manager
     * @return
     */
    @Override
    public SetMeta<Manager> updateRole(Integer id, Manager manager) throws UserException {
        Role role = roleMapper.selectById(manager.getRid());
        if(manager.getRid() == null || manager.getRid().equals("") || role == null) throw new UserException("角色信息错误");

        SetMeta<Manager> setMeta = new SetMeta<>();
        Manager select = managerMapper.selectById(id);
        select.setRid(manager.getRid());
        int update = managerMapper.update(select, Wrappers.<Manager>lambdaQuery().eq(Manager::getId, id));
        if (update == 1) {
            select.setPassword(null);
            select.setType(null);
            setMeta.setSuccess(select, "设置角色成功");
            return setMeta;
        }
        setMeta.setError("设置角色失败");
        return setMeta;
    }

    @Override
    public Manager getUsername(String username) {
        return managerMapper.selectOne(Wrappers.<Manager>lambdaQuery().eq(Manager::getUsername, username));
    }

    /**
     * 获取权限并添加到缓存中
     * @param id
     * @return
     */
    @Override
    public String getUserAuthorityInfo(Integer id) {
        Manager manager = managerMapper.selectById(id);
        String authority = "";

        if (redisUtil.hasKey("GranteAuthority:" + manager.getUsername())) {
            authority = (String) redisUtil.get("GranteAuthority:" + manager.getUsername());
        } else {
            if (manager.getRid() == 0) {
                authority = String.valueOf(manager.getRid()).concat(",");

                List<Right> rights = rightsMapper.selectList(null);
                String rightCodes = rights.stream().map(r -> String.valueOf(r.getId())).collect(Collectors.joining(","));
                authority = authority.concat(rightCodes);
            } else {
                Role role = roleMapper.selectById(manager.getRid());
                authority = String.valueOf(manager.getRid()).concat(",");
                authority = authority.concat(role.getPsIds());
            }

            redisUtil.set("GranteAuthority:" + manager.getUsername(), authority, 60 * 60);
        }

        return authority;
    }

    /**
     * 删除某个用户的权限信息
     * @param username
     */
    @Override
    public void clearUserAuthorityInfo(String username) {
        redisUtil.del("GranteAuthority:" + username);
    }

    /**
     * 删除所有与该角色关联的用户的权限信息
     * @param roleId
     */
    @Override
    public void clearUserAuthorityInfoByRoleId(Long roleId) {


    }

    /**
     * 删除所有与该菜单关联的所有用户的权限信息
     * @param menuId
     */
    @Override
    public void clearUserAuthorityInfoByMenuId(Long menuId) {

    }
}
